package top.fkxuexi.blogapi.core.filters;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PjaxFilter implements HandlerInterceptor {


    String noInteceptorUrl = ".*/((login)|(index/page)|(/*.*))";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.err.println(request.getRequestURI());
        // 如果是请求静态文件的放行
        if(request.getRequestURI().contains("static")){
            return true;
        }

        // 如果是ajax的请求的话 放行
        if ("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))){
            return true;
        }
        // 如果是pjax的请求的话，也是需要放行的
        if ("true".equalsIgnoreCase(request.getHeader("X-PJAX"))){
            return true;
        }
        // 如果是这些路径同样的放行
        if (request.getRequestURI().matches(noInteceptorUrl)){
            return true;
        }
        response.sendRedirect("/index/page");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
